<?php
/**
 * The Controller
 * 
 * @package Controller
 * @author Shuky
 * @since v1.0
 * @version $Id: Controller.php 8 2010-04-03 12:11:43Z shuky $
 */
namespace SFramework;

class Controller
{
    // 自身实例，以实现单件模式
    protected static $_instance = null;
    
    // Request请求实例
    protected $_request = null;
    
    // Module
    protected $_module = 'index';
    
    // Controller
    protected $_controller = 'index';
    
    // Action
    protected $_action = 'index';
    
    
	public function __construct()
	{
		if (null === $this->_request) {
		    $this->_request = Request::getInstance();
		}
		$path = $this->getRequest()->getPathInfo();
		print_r($path);
		if ($path != null) {
			$path = explode('/', $path);
			!isset($path[0]) || $this->_module = $path[0];
			!isset($path[1]) || $this->_controller = $path[1];
			!isset($path[2]) || $this->_action = $path[2];
		}
	}
	
	
    /**
     * 获取实例
     * @return \SFrame\Controller
     */
	public static function getInstance()
	{
		if (null === self::$_instance) {
			self::$_instance = new self();
		}
		return self::$_instance;
	}
	
	
	/**
	 * 获取Module
	 * @return string
	 */
	public function getModule()
	{
		return $this->_module;
	}
	
	
	/**
	 * 获取Controller
	 * @return string
	 */
	public function getController()
	{
		return $this->_controller;
	}
	
	
	/**
	 * 获取Action
	 * @return string
	 */
	public function getAction()
	{
		return $this->_action;
	}
	
	
	/**
	 * 获取Request实例
	 * @return \SFrame\Request
	 */
	public function getRequest()
	{
		return $this->_request;
	}
	
	
	/**
	 * 控制分发
	 */
	public function dispatch()
	{
	    $className = ucfirst($this->getController()) .'Controller';
	    include APPLICATION_PATH .'/'. $this->getModule() .'/controllers/'. $className .'.php';
		$action = $this->getAction() .'Action';
		$controller = new $className();
		if (!method_exists($controller, $action)) {
			throw new SException\Controller('请求动作不存在');
		}
		return $controller->$action();
	}
}